import 'dart:io';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import '../model/health_record.dart';
import '../model/baby.dart';
import '../service/database_service.dart';
import '../model/reminder.dart';
import '../service/theme_notifier.dart';
import '../service/theme_service.dart';
import '../theme/neumorphic_theme.dart';
import '../ui/ui.dart';
import '../widgets/gradient_app_bar.dart';

class DashboardTab extends StatefulWidget {
  @override
  _DashboardTabState createState() => _DashboardTabState();
}

class _DashboardTabState extends State<DashboardTab> {
  Baby? _selectedBaby;
  List<Baby> _babies = []; // Add this line to store all babies
  final _refreshController = GlobalKey<RefreshIndicatorState>();
  String? _pressedButton;
  String? _pressedRecord;

  @override
  void initState() {
    super.initState();
    _loadBabies();
  }

  Future<void> _loadBabies() async {
    try {
      final babies = await DatabaseService().getAllBabies();
      final defaultBaby = await DatabaseService().getDefaultBaby();

      setState(() {
        _babies = babies;
        _selectedBaby =
            defaultBaby ?? (babies.isNotEmpty ? babies.first : null);
      });
    } catch (e) {
      debugPrint('Failed to load babies: $e');
    }
  }

  // Add refresh method
  Future<void> _handleRefresh() async {
    await Future.wait([
      _loadBabies(), // Add this line
      if (_selectedBaby != null) ...[
        DatabaseService().getDailySummary(_selectedBaby!.id),
        DatabaseService().getRecentRecords(limit: 5),
        DatabaseService().getTodayReminders(_selectedBaby!.id),
      ],
    ]);
  }

  @override
  Widget build(BuildContext context) {
    if (_selectedBaby == null) {
      return Center(child: CircularProgressIndicator());
    }

    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(_selectedBaby?.name??'健康宝宝'),
            Text('健康成长${_getGrowthTimeText()}',style:Theme.of(context).textTheme.bodySmall?.merge(TextStyle(
              color: Colors.white
            )))
          ],
        )
      ),
      body: RefreshIndicator(
        key: _refreshController,
        onRefresh: _handleRefresh,
        child: CustomScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          slivers: [
            SliverPadding(
              padding: EdgeInsets.all(16),
              sliver: SliverList(delegate: SliverChildListDelegate([
                _buildHealthSummary(),
                SizedBox(height: 16),
                _buildQuickActions(),
                SizedBox(height: 16),
                _buildRecentEvents(),
                SizedBox(height: 16),
                _buildReminders(),
              ])),
            )
          ],
        ),
      ),
    );
  }

  // Add helper method to get growth time text
  String _getGrowthTimeText() {
    if (_selectedBaby == null) return '';

    final birthDate = _selectedBaby!.birthDate;
    final now = DateTime.now();
    final difference = now.difference(birthDate);

    final years = difference.inDays ~/ 365;
    final months = (difference.inDays % 365) ~/ 30;
    final days = difference.inDays % 30;

    String growthText = '';
    if (years > 0) {
      growthText += '$years岁';
    }
    if (months > 0 || years > 0) {
      growthText += '$months个月';
    }
    growthText += '$days天';

    return growthText;
  }

  // Update _buildBabyInfo to use theme colors
  Widget _buildBabyInfo() {
    if (_selectedBaby == null) return const Text('宝宝健康');
    final themeColors =
        ThemeService.themeColors[ThemeNotifier.instance.currentTheme]!;

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          padding: const EdgeInsets.all(2),
          decoration: NeumorphicTheme.insetDecoration(
            baseColor: Theme.of(context).scaffoldBackgroundColor,
            borderRadius: BorderRadius.circular(24),
          ),
          child:
              _selectedBaby!.avatarUrl != null
                  ? CircleAvatar(
                    backgroundImage: FileImage(File(_selectedBaby!.avatarUrl!)),
                    radius: 20,
                  )
                  : CircleAvatar(
                    child: Text(
                      _selectedBaby!.name[0],
                      style: TextStyle(
                        color: themeColors.primary,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    radius: 20,
                    backgroundColor: Theme.of(context).scaffoldBackgroundColor,
                  ),
        ),
        const SizedBox(width: 12),
        Text(
          _selectedBaby!.name,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: themeColors.primary,
          ),
        ),
      ],
    );
  }

  // Update _buildGrowthTime to use theme colors
  Widget _buildGrowthTime() {
    return Padding(
      padding: const EdgeInsets.only(top: 4),
      child: Text(
        _getGrowthTimeText(),
        style: const TextStyle(fontSize: 14, color: Colors.white70),
      ),
    );
  }

  Widget _buildHealthSummary() {
    if (_selectedBaby == null) return const SizedBox.shrink();
    final backgroundColor = Theme.of(context).scaffoldBackgroundColor;

    return Container(
      decoration: NeumorphicTheme.surfaceDecoration(
        baseColor: backgroundColor,
        borderRadius: BorderRadius.circular(20),
      ),
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('24小时概览', style: Theme.of(context).textTheme.titleMedium),
          const SizedBox(height: 16),
          FutureBuilder<Map<String, dynamic>>(
            future: DatabaseService().getDailySummary(_selectedBaby!.id),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return const Center(child: CircularProgressIndicator());
              }

              final data = snapshot.data!;
              return Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      _buildNeumorphicSummaryItem(
                        context,
                        '喂奶总量',
                        '${data['feedingAmount'] ?? 0}ml',
                        Icons.local_cafe,
                      ),
                      _buildNeumorphicSummaryItem(
                        context,
                        '换尿布',
                        '${data['diaperCount'] ?? 0}次',
                        Icons.cleaning_services,
                      ),
                      _buildNeumorphicSummaryItem(
                        context,
                        '体温',
                        '${data['lastTemperature'] ?? '--'}°C',
                        Icons.thermostat,
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  _buildLastEventTimes(),
                ],
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildNeumorphicSummaryItem(
    BuildContext context,
    String label,
    String value,
    IconData icon,
  ) {
    final backgroundColor = Theme.of(context).scaffoldBackgroundColor;

    return Container(
      padding: const EdgeInsets.all(12),
      decoration: NeumorphicTheme.surfaceDecoration(
        baseColor: backgroundColor,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(10),
            decoration: NeumorphicTheme.insetDecoration(
              baseColor: backgroundColor,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(icon, size: 24, color: Theme.of(context).primaryColor),
          ),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: Theme.of(context).primaryColor,
            ),
          ),
          const SizedBox(height: 4),
          Text(label, style: TextStyle(fontSize: 12, color: Colors.grey[600])),
        ],
      ),
    );
  }

  Widget _buildRecentEvents() {
    final backgroundColor = Theme.of(context).scaffoldBackgroundColor;

    return Container(
      decoration: NeumorphicTheme.surfaceDecoration(
        baseColor: backgroundColor,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Text('最近记录', style: Theme.of(context).textTheme.titleMedium),
          ),
          FutureBuilder<List<HealthRecord>>(
            future: DatabaseService().getRecentRecords(
              babyId: _selectedBaby!.id,
              limit: 5,
            ),
            builder: (context, snapshot) {
              if (!snapshot.hasData || snapshot.data!.isEmpty) {
                return const Padding(
                  padding: EdgeInsets.all(16),
                  child: Text('暂无记录'),
                );
              }

              return ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: snapshot.data!.length,
                padding: const EdgeInsets.all(16),
                separatorBuilder:
                    (context, index) => const SizedBox(height: 16),
                itemBuilder: (context, index) {
                  final record = snapshot.data![index];
                  return GestureDetector(
                    onTapDown:
                        (_) => setState(() => _pressedRecord = record.id),
                    onTapUp: (_) {
                      setState(() => _pressedRecord = null);
                      _showRecordDetails(record);
                    },
                    onTapCancel: () => setState(() => _pressedRecord = null),
                    child: AnimatedContainer(
                      duration: const Duration(milliseconds: 150),
                      decoration: BoxDecoration(
                        color: backgroundColor,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow:
                            _pressedRecord == record.id
                                ? [
                                  BoxShadow(
                                    color: Colors.white.withOpacity(0.3),
                                    offset: const Offset(-2, -2),
                                    blurRadius: 4,
                                  ),
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.2),
                                    offset: const Offset(2, 2),
                                    blurRadius: 4,
                                  ),
                                ]
                                : [
                                  BoxShadow(
                                    color: Colors.white.withOpacity(0.8),
                                    offset: const Offset(-4, -4),
                                    blurRadius: 8,
                                  ),
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.1),
                                    offset: const Offset(4, 4),
                                    blurRadius: 8,
                                  ),
                                ],
                      ),
                      padding: const EdgeInsets.all(16),
                      child: Row(
                        children: [
                          Container(
                            width: 48,
                            height: 48,
                            decoration: BoxDecoration(
                              color: backgroundColor,
                              shape: BoxShape.circle,
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.1),
                                  offset: const Offset(-2, -2),
                                  blurRadius: 4,
                                  spreadRadius: 0,
                                ),
                                BoxShadow(
                                  color: Colors.white.withOpacity(0.8),
                                  offset: const Offset(2, 2),
                                  blurRadius: 4,
                                  spreadRadius: 0,
                                ),
                              ],
                            ),
                            child: Icon(
                              record.type.icon,
                              color: getRecordTypeColor(record.type),
                              size: 24,
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  '${getRecordTypeText(record.type)} · ${_formatRecordData(record)}',
                                  style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  _formatDateTime(record.timestamp),
                                  style: TextStyle(
                                    color: Colors.grey[600],
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Icon(Icons.chevron_right, color: Colors.grey[400]),
                        ],
                      ),
                    ),
                  );
                },
              );
            },
          ),
        ],
      ),
    );
  }

  void _showRecordDetails(HealthRecord record) {
    final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
    final themeColors = ThemeService.themeColors[ThemeNotifier.instance.currentTheme]!;

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Container(
        margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
        decoration: NeumorphicTheme.surfaceDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(24),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Handle bar
            Container(
            margin: const EdgeInsets.symmetric(vertical: 12),
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Title with icon
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: NeumorphicTheme.surfaceDecoration(
                    baseColor: backgroundColor,
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.all(12),
                        decoration: NeumorphicTheme.insetDecoration(
                          baseColor: backgroundColor,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Icon(
                          record.type.icon,
                          color: getRecordTypeColor(record.type),
                          size: 24,
                        ),
                      ),
                      const SizedBox(width: 16),
                      Text(
                        getRecordTypeText(record.type),
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
                // Details
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: NeumorphicTheme.insetDecoration(
                    baseColor: backgroundColor,
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(Icons.info_outline, 
                            color: themeColors.primary,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            _formatRecordData(record),
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 12),
                      Row(
                        children: [
                          Icon(Icons.access_time,
                            color: themeColors.primary,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            DateFormat('yyyy-MM-dd HH:mm').format(record.timestamp),
                            style: const TextStyle(fontSize: 14),
                          ),
                        ],
                      ),
                      if (record.data['notes']?.isNotEmpty == true) ...[
                        const SizedBox(height: 12),
                        Row(
                          children: [
                            Icon(Icons.notes,
                              color: themeColors.primary,
                              size: 20,
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                record.data['notes'],
                                style: const TextStyle(fontSize: 14),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ],
                  ),
                ),
                const SizedBox(height: 24),
                // Close button
                Center(
                  child: GestureDetector(
                    onTap: () => Navigator.pop(context),
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 32,
                        vertical: 12,
                      ),
                      decoration: NeumorphicTheme.surfaceDecoration(
                        baseColor: backgroundColor,
                        borderRadius: BorderRadius.circular(24),
                      ),
                      child: Text(
                        '关闭',
                        style: TextStyle(
                          color: themeColors.primary,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 8),
              ],
            ),
          ),
        ],
      ),
    ));
  }

  // 辅助方法
  void _handleQuickAction(String action) {
    switch (action) {
      case '喂奶':
        showRecordDialogByType(context, RecordType.feeding, _selectedBaby!.id);
        break;
      case '换尿布':
        showRecordDialogByType(context, RecordType.diaper, _selectedBaby!.id);
        break;
      case '测体温':
        showRecordDialogByType(
          context,
          RecordType.temperature,
          _selectedBaby!.id,
        );
        break;
      case '用药':
        showRecordDialogByType(context, RecordType.medicine, _selectedBaby!.id);
        break;
    }
  }

  String _formatRecordData(HealthRecord record) {
    // 根据记录类型格式化数据
    switch (record.type) {
      case RecordType.feeding:
        return '${record.data['amount']}ml';
      case RecordType.temperature:
        return '${record.data['temperature']}°C';
      default:
        return '';
    }
  }

  String _formatDateTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inMinutes < 60) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inHours < 24) {
      return '${difference.inHours}小时前';
    } else {
      return DateFormat('MM-dd HH:mm').format(dateTime);
    }
  }

  Widget _buildQuickActions() {
    final itemWidth =
        (MediaQuery.of(context).size.width - 32 - 48) /
        4; // Screen width - padding - spacing
    final itemHeight = itemWidth * 1.2; // Maintain aspect ratio

    return GridView.count(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      crossAxisCount: 4,
      mainAxisSpacing: 16,
      crossAxisSpacing: 16,
      padding: const EdgeInsets.all(16),
      childAspectRatio: itemWidth / itemHeight, // Add proper aspect ratio
      children: [
        _buildQuickActionItem('喂奶', Icons.local_cafe),
        _buildQuickActionItem('换尿布', Icons.cleaning_services),
        _buildQuickActionItem('测体温', Icons.thermostat),
        _buildQuickActionItem('用药', Icons.medication),
      ],
    );
  }

  Widget _buildQuickActionItem(String label, IconData icon) {
    final backgroundColor = Theme.of(context).scaffoldBackgroundColor;

    return GestureDetector(
      onTapDown: (_) => setState(() => _pressedButton = label),
      onTapUp: (_) {
        setState(() => _pressedButton = null);
        _handleQuickAction(label);
      },
      onTapCancel: () => setState(() => _pressedButton = null),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 150),
        decoration: BoxDecoration(
          color: backgroundColor,
          borderRadius: BorderRadius.circular(16),
          boxShadow:
              _pressedButton == label
                  ? [
                    BoxShadow(
                      color: Colors.white.withOpacity(0.3),
                      offset: const Offset(-2, -2),
                      blurRadius: 4,
                    ),
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      offset: const Offset(2, 2),
                      blurRadius: 4,
                    ),
                  ]
                  : [
                    BoxShadow(
                      color: Colors.white.withOpacity(0.8),
                      offset: const Offset(-4, -4),
                      blurRadius: 8,
                    ),
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      offset: const Offset(4, 4),
                      blurRadius: 8,
                    ),
                  ],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min, // Add this
          children: [
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: backgroundColor,
                shape: BoxShape.circle,
                boxShadow:
                    _pressedButton == label
                        ? [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            offset: const Offset(-2, -2),
                            blurRadius: 4,
                          ),
                          BoxShadow(
                            color: Colors.white.withOpacity(0.8),
                            offset: const Offset(2, 2),
                            blurRadius: 4,
                          ),
                        ]
                        : [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            offset: const Offset(-4, -4),
                            blurRadius: 8,
                          ),
                          BoxShadow(
                            color: Colors.white.withOpacity(0.8),
                            offset: const Offset(4, 4),
                            blurRadius: 8,
                          ),
                        ],
              ),
              child: Icon(
                icon,
                color: Theme.of(context).primaryColor,
                size: 24,
              ),
            ),
            const SizedBox(height: 8),
            FittedBox(
              // Wrap text in FittedBox
              child: Text(
                label,
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[800],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildReminders() {
    final backgroundColor = Theme.of(context).scaffoldBackgroundColor;

    return Container(
      decoration: NeumorphicTheme.surfaceDecoration(
        baseColor: backgroundColor,
        borderRadius: BorderRadius.circular(20),
      ),
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('重要提醒', style: Theme.of(context).textTheme.titleMedium),
              TextButton(
                onPressed:
                    () => Navigator.pushNamed(
                      context,
                      '/reminders',
                      arguments: _selectedBaby?.id ?? '',
                    ),
                child: const Text('查看全部'),
              ),
            ],
          ),
          const SizedBox(height: 8),
          FutureBuilder<List<Reminder>>(
            future: DatabaseService().getTodayReminders(_selectedBaby!.id),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return const Center(child: CircularProgressIndicator());
              }

              final reminders = snapshot.data!;
              if (reminders.isEmpty) {
                return const Text('今日无提醒');
              }

              return Column(
                children:
                    reminders
                        .map(
                          (reminder) => Container(
                            margin: const EdgeInsets.symmetric(vertical: 4),
                            padding: const EdgeInsets.all(12),
                            decoration: NeumorphicTheme.insetDecoration(
                              baseColor: backgroundColor,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Row(
                              children: [
                                Icon(
                                  reminder.type.icon,
                                  color: Theme.of(context).primaryColor,
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        reminder.title,
                                        style: const TextStyle(
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      Text(
                                        DateFormat('HH:mm').format(
                                          reminder.scheduleTime as DateTime,
                                        ),
                                        style: TextStyle(
                                          color: Colors.grey[600],
                                          fontSize: 12,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                Container(
                                  padding: const EdgeInsets.all(8),
                                  decoration: NeumorphicTheme.surfaceDecoration(
                                    baseColor: backgroundColor,
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Icon(
                                    Icons.check_circle_outline,
                                    color: Theme.of(context).primaryColor,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                        .toList(),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildLastEventTimes() {
    return FutureBuilder<Map<String, DateTime?>>(
      future: DatabaseService().getLastEventTimes(_selectedBaby!.id),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return const SizedBox.shrink();

        final data = snapshot.data!;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildLastEventTime(
              '上次喂奶',
              data['feeding'],
              const Duration(hours: 4),
            ),
            _buildLastEventTime(
              '上次换尿布',
              data['diaper'],
              const Duration(hours: 3),
            ),
            _buildLastEventTime(
              '上次测温',
              data['temperature'],
              const Duration(hours: 6),
            ),
          ],
        );
      },
    );
  }

  Widget _buildLastEventTime(String label, DateTime? time, Duration threshold) {
    if (time == null) return const SizedBox.shrink();

    final difference = DateTime.now().difference(time);
    final needsAttention = difference > threshold;

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Text(
            '$label: ${_formatTimeDifference(difference)}',
            style: TextStyle(
              color: needsAttention ? Colors.red : Colors.grey[600],
              fontWeight: needsAttention ? FontWeight.bold : FontWeight.normal,
            ),
          ),
          if (needsAttention) ...[
            const SizedBox(width: 8),
            const Icon(Icons.warning, color: Colors.red, size: 16),
          ],
        ],
      ),
    );
  }

  String _formatTimeDifference(Duration difference) {
    if (difference.inMinutes < 60) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inHours < 24) {
      return '${difference.inHours}小时${difference.inMinutes % 60}分钟前';
    } else {
      return '${difference.inDays}天前';
    }
  }
}
